from abc import ABC, abstractmethod

# Component: 抽象构件
class Component(ABC):
    def __init__(self, name: str):
        self._name = name

    @abstractmethod
    def add(self, component: 'Component'):
        pass

    @abstractmethod
    def remove(self, component: 'Component'):
        pass

    @abstractmethod
    def display(self, depth: int):
        pass

# Leaf: 叶子构件
class Leaf(Component):
    def __init__(self, name: str):
        super().__init__(name)

    def add(self, component: Component):
        pass  # 叶子节点不能添加子节点

    def remove(self, component: Component):
        pass  # 叶子节点没有子节点可以移除

    def display(self, depth: int):
        print(' ' * depth + f'- {self._name}')

# Composite: 组合构件
class Composite(Component):
    def __init__(self, name: str):
        super().__init__(name)
        self._children = []

    def add(self, component: Component):
        self._children.append(component)

    def remove(self, component: Component):
        self._children.remove(component)

    def display(self, depth: int):
        print(' ' * depth + f'+ {self._name}')
        for child in self._children:
            child.display(depth + 2)

# Client: 客户端
class Client:
    def __init__(self, component: Component):
        self._component = component

    def execute(self):
        self._component.display(0)

# Usage
if __name__ == "__main__":
    # 创建叶子节点
    leaf1 = Leaf("Leaf1")
    leaf2 = Leaf("Leaf2")

    # 创建组合节点并添加叶子节点
    composite1 = Composite("Composite1")
    composite1.add(leaf1)
    composite1.add(leaf2)

    # 创建另一个组合节点并添加 composite1
    composite2 = Composite("Composite2")
    composite2.add(composite1)

    # 客户端使用
    client = Client(composite2)
    client.execute()

# 代码实现
#     + Composite2
#     + Composite1
#     - Leaf1
#     - Leaf2
